package com.tedu07.lcl.controller;

import com.tedu07.lcl.entity.File;
import com.tedu07.lcl.entity.FileList;
import com.tedu07.lcl.entity.Resources;
import com.tedu07.lcl.entity.User;
import com.tedu07.lcl.mapper.FileMapper;
import com.tedu07.lcl.mapper.ResourcesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class FileController {

    @Autowired(required = false)
    FileMapper fileMapper;
    @Autowired(required = false)
    ResourcesMapper resourcesMapper;

    //上传文件
    @RequestMapping("/file/addFile")
    public int addFile(MultipartFile file, HttpSession session) throws IOException {
        if (file.getOriginalFilename().equals("")){
            return 2;   //没有选择文件,直接退出
        }
        //生成MD5
        String md5Str = "";
        md5Str = DigestUtils.md5DigestAsHex(file.getBytes());
        System.out.println(md5Str);
        //获取文件名和后缀
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf('.'));
        User user = (User)session.getAttribute("user");
        //查询MD5是否存在
        Resources resources = resourcesMapper.checkMD5(md5Str);
        System.out.println(resources);
        if (resources == null){
            //资源不存在,创建资源对象

            String dirPath = "E:/upload/userFile/"+user.getUid()+"/"+user.getDid()+"/";  //拼接文件目录
            java.io.File dir = new java.io.File(dirPath);
            if (!dir.exists()) {      //如果没目录就创建一个
                dir.mkdirs();
            }
            String uuidName = UUID.randomUUID()+suffix;
            String filePath = dirPath.substring(dirPath.indexOf("/userFile")) + uuidName;
            resources = new Resources();
            resources.setName(uuidName);
            resources.setMd5(md5Str);
            resources.setPath(filePath);
            resources.setSize(file.getSize());
            resources.setUpUid(user.getUid());
            resources.setUpTime(new Date());
            resources.setDownTimes(0);
            resources.setQuantity(0);
            resources.setGmtCreate(null);
            resources.setGmtModified(null);
            //转存文件+存resources数据库
            try {
                resourcesMapper.addResources(resources);
                resources.setRid(resourcesMapper.selectIdByFilePath(filePath).getRid());
                file.transferTo(new java.io.File("E:/upload"+filePath));
            } catch (IOException e) {
                System.out.println("转存文件时发生异常");
                e.printStackTrace();
            }

        }
        else {
            //资源已存在
            System.out.println("资源已存在");
        }

        //生成文件对象
        File f = new File();
        f.setRid(resources.getRid());
        f.setFfid(null);
        f.setDid(user.getDid());
        f.setUid(user.getUid());
        f.setFname(fileName);
        f.setSuffix(suffix);
        //按后缀名定义类型 待补充...
        if (suffix.equals(".mp3") || suffix.equals(".wma") || suffix.equals(".midi") || suffix.equals(".flac"))
            f.setType("音乐");
        else if (suffix.equals(".mp4") || suffix.equals(".avi") || suffix.equals(".rm") || suffix.equals(".rmvb"))
            f.setType("视频");
        else if (suffix.equals(".txt") || suffix.equals(".doc"))
            f.setType("文档");
        else if (suffix.equals(".jpg") || suffix.equals(".png"))
            f.setType("图片");
        else
            f.setType("其它");
        f.setSize(file.getSize());
        f.setStatus(0);
        //存file数据库
        fileMapper.add(f);
        resourcesMapper.increase(resources.getRid());

        return 1;   //上传成功
    }

    //删除文件
    @RequestMapping("/file/del")
    public int del(Integer fid){
        int rid = fileMapper.selectRidByFid(fid).getRid();   //得到对应的资源id
        fileMapper.del(fid);

        resourcesMapper.reduce(rid);
        Resources resources = resourcesMapper.selectById(rid);
        if (resources.getQuantity() == 0){
            //删除数据库记录
            resourcesMapper.deleteById(rid);
            //删除本地资源
            java.io.File file = new java.io.File("E:/upload"+resources.getPath());
            file.delete();
            System.out.println(rid+"删完了");
        }

        return 1;
    }

    //管理员删除文件
    @RequestMapping("/file/superDel")
    public int superDel(Integer fid,HttpSession session){
        User user = (User)session.getAttribute("user");
        if (user.getStatus() != 1){     //非管理员
            return 0;
        }
        else {      //管理员
            int rid = fileMapper.selectRidByFid(fid).getRid();
            Resources resources = resourcesMapper.selectById(rid);
            fileMapper.delAllByRid(rid);
            resourcesMapper.deleteById(rid);
            java.io.File file = new java.io.File("E:/upload"+resources.getPath());
            file.delete();

            System.out.println(rid+"删完了");
            return 1;
        }

    }

    //更改文件权限
    @RequestMapping("/file/changeStatus")
    public int changeStatus(int status,int fid){
        fileMapper.changeStatus(status,fid);
        return 1;
    }


}
